import { PayloadAction, createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { Picture } from '../../api/picture'
import { AsyncState, ListState } from '..'
import { apiGetPublicPictureList } from '../../api/public'
type PublicPictureState = AsyncState & ListState<Picture> &{
    current?:Picture
}

const initialState: PublicPictureState = {
    status: 'idle',
    error: null,
    list: [],
    pager: {
        totalRows: 0,
        pageSize: 20,
        page: 1,
    }
}
export const fetchPublicPictures = createAsyncThunk('public/fetchPublicPictures', apiGetPublicPictureList)
export const publicPictureSlice = createSlice({
    name: 'publicPicture',
    initialState: initialState,
    reducers: {
        publicPitcturePagerAdd(state) {
            state.pager.page = state.pager.page + 1
            state.status = 'idle'
        },
        detailReset(state) {
            state.status = initialState.status
            state.error = initialState.error
            state.list = initialState.list
            state.pager = initialState.pager
        },
        changeCurrent(state,action:PayloadAction<number>){
            state.current = state.list.find((i)=> i.id === action.payload)
        }
    },
    extraReducers(builder) {
        builder
            .addCase(fetchPublicPictures.pending, (state) => {
                state.status = 'loading'
            })
            .addCase(fetchPublicPictures.fulfilled, (state, action) => {
                state.status = 'succeeded'
                state.list = state.list.concat(action.payload.list)
                state.pager = action.payload.pager
            })
            .addCase(fetchPublicPictures.rejected, (state) => {
                state.status = 'failed'
                state.error = '获取详细信息列表失败'
            })
    }
})
export const { publicPitcturePagerAdd, detailReset ,changeCurrent} = publicPictureSlice.actions
export default publicPictureSlice.reducer